package com.easy.work.function;

import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.widget.ImageView;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.base.syslib.Logs;
import com.base.syslib.action.PermissionManager;
import com.easy.work.MainActivity;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.CommonValue;
import com.easy.work.app.MyApplication;
import com.easy.work.location.LocationService;
import com.squareup.picasso.Picasso;

import java.util.ArrayList;

/**
 * Created by zzgpc on 2017-8-24.
 */

public class SplashActivity extends Activity {
    private String tag = "SplashActivity";
    private final int SDK_PERMISSION_REQUEST = 127;
    private String permissionInfo;
    private ImageView imageView;


    /**
     * 定位
     */
    private LocationService locationService;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                if (!AppSession.getInstance().getNaved()) {
                    startActivity(new Intent(SplashActivity.this, NavActivity.class));
                    finish();
                    return;
                }

                AppSession.getInstance().setNaved(true);
                LoginActivity.start(SplashActivity.this);
                finish();
            } catch (Exception e) {
                LoginActivity.start(SplashActivity.this);
                finish();
            }

        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_splash);
        if (getIntent() != null && getIntent().hasExtra(CommonValue.isExit)) {
            if (getIntent().getBooleanExtra(CommonValue.isExit, false)) {
                finish();
                return;
            }
        }
        imageView = (ImageView) findViewById(R.id.imageView);

        Picasso.with(this)
                .load(R.mipmap.splash_screen)
                .into(imageView);
        if (Build.VERSION.SDK_INT >= 23) {
            PermissionManager.requestIEMPermission(this);
            PermissionManager.requestSDPermission(this);
            PermissionManager.requestCameraPermission(this);
            ArrayList<String> permissions = new ArrayList<String>();
        }
        getPersimmions();
        initLocation();
        handler.sendEmptyMessageDelayed(1, 3 * 1000);
    }

    private void initLocation() {
        locationService = ((MyApplication) getApplication()).locationService;
        //获取locationservice实例，建议应用中只初始化1个location实例，然后使用，可以参考其他示例的activity，都是通过此种方式获取locationservice实例的
        locationService.registerListener(mListener);
        //注册监听
        int type = 0;
        if (getIntent() != null && getIntent().hasExtra("from")) {
            type = getIntent().getIntExtra("from", 0);
        }

        if (type == 0) {
            locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        } else if (type == 1) {
            locationService.setLocationOption(locationService.getOption());
        }
        locationService.start();// 定位SDK
    }

    /*****
     *
     * 定位结果回调，重写onReceiveLocation方法，可以直接拷贝如下代码到自己工程中修改
     *
     */
    private BDAbstractLocationListener mListener = new BDAbstractLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {


            // TODO Auto-generated method stub
            if (null != location && location.getLocType() != BDLocation.TypeServerError) {
                Logs.e(tag, "定位成功....");
                StringBuffer sb = new StringBuffer(256);
                sb.append("time : ");
                /**
                 * 时间也可以使用systemClock.elapsedRealtime()方法 获取的是自从开机以来，每次回调的时间；
                 * location.getTime() 是指服务端出本次结果的时间，如果位置不发生变化，则时间不变
                 */
                final BDLocation location1 = location;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                        String cityCode = StringUtil.getCityCode(getApplicationContext(), location1.getCity());
                        AppSession.getInstance().setCityCodeForName(location1.getCity());
//                        AppSession.saveAppSessionData(SPKey.cityCode, code);
                    }
                }).start();

                float dLatitude = (float) location.getLatitude();
                float dLongitude = (float) location.getLongitude();
                if (dLatitude != 0.0f && dLongitude != 0.0f) {
                    String latitude = String.valueOf(location.getLatitude());
                    String longitude = String.valueOf(location.getLongitude());
                    Logs.e(tag, "Latitude = " + latitude + "    longitude = " + longitude + "     city = " + location.getCity());
                    AppSession.getInstance().setLatitude(latitude);
                    AppSession.getInstance().setLontitude(longitude);
                    AppSession.getInstance().setCityName(location.getCity());
                }


                if (location.getLocType() == BDLocation.TypeGpsLocation) {// GPS定位结果
                    sb.append("\nspeed : ");
                    sb.append(location.getSpeed());// 速度 单位：km/h
                    sb.append("\nsatellite : ");
                    sb.append(location.getSatelliteNumber());// 卫星数目
                    sb.append("\nheight : ");
                    sb.append(location.getAltitude());// 海拔高度 单位：米
                    sb.append("\ngps status : ");
                    sb.append(location.getGpsAccuracyStatus());// *****gps质量判断*****
                    sb.append("\ndescribe : ");
                    sb.append("gps定位成功");
                } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {// 网络定位结果
                    // 运营商信息
                    if (location.hasAltitude()) {// *****如果有海拔高度*****
                        sb.append("\nheight : ");
                        sb.append(location.getAltitude());// 单位：米
                    }
                    sb.append("\noperationers : ");// 运营商信息
                    sb.append(location.getOperators());
                    sb.append("\ndescribe : ");
                    sb.append("网络定位成功");
                } else if (location.getLocType() == BDLocation.TypeOffLineLocation) {// 离线定位结果
                    sb.append("\ndescribe : ");
                    sb.append("离线定位成功，离线定位结果也是有效的");
                } else if (location.getLocType() == BDLocation.TypeServerError) {
                    sb.append("\ndescribe : ");
                    sb.append("服务端网络定位失败，可以反馈IMEI号和大体定位时间到loc-bugs@baidu.com，会有人追查原因");
                } else if (location.getLocType() == BDLocation.TypeNetWorkException) {
                    sb.append("\ndescribe : ");
                    sb.append("网络不同导致定位失败，请检查网络是否通畅");
                } else if (location.getLocType() == BDLocation.TypeCriteriaException) {
                    sb.append("\ndescribe : ");
                    sb.append("无法获取有效定位依据导致定位失败，一般是由于手机的原因，处于飞行模式下一般会造成这种结果，可以试着重启手机");
                }
                Logs.e(tag, sb.toString());
//                logMsg(sb.toString());
            }
            locationService.start();
//            locationService.stop();
        }

    };

    @TargetApi(23)
    private void getPersimmions() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            ArrayList<String> permissions = new ArrayList<String>();
            /***
             * 定位权限为必须权限，用户如果禁止，则每次进入都会申请
             */
            // 定位精确位置
            if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_FINE_LOCATION);
            }
            if (checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                permissions.add(Manifest.permission.ACCESS_COARSE_LOCATION);
            }
            /*
             * 读写权限和电话状态权限非必要权限(建议授予)只会申请一次，用户同意或者禁止，只会弹一次
			 */
            // 读写权限
            if (addPermission(permissions, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissionInfo += "Manifest.permission.WRITE_EXTERNAL_STORAGE Deny \n";
            }
//            // 读取电话状态权限
//            if (addPermission(permissions, Manifest.permission.READ_PHONE_STATE)) {
//                permissionInfo += "Manifest.permission.READ_PHONE_STATE Deny \n";
//            }

            if (permissions.size() > 0) {
                requestPermissions(permissions.toArray(new String[permissions.size()]), SDK_PERMISSION_REQUEST);
            }
        }
    }


    @TargetApi(23)
    private boolean addPermission(ArrayList<String> permissionsList, String permission) {
        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) { // 如果应用没有获得对应权限,则添加到列表中,准备批量申请
            if (shouldShowRequestPermissionRationale(permission)) {
                return true;
            } else {
                permissionsList.add(permission);
                return false;
            }

        } else {
            return true;
        }
    }

    @TargetApi(23)
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

    }
//    /**
//     * 用户进行权限设置后的回调函数 , 来响应用户的操作，无论用户是否同意权限，Activity都会
//     * 执行此回调方法，所以我们可以把具体操作写在这里
//     *
//     * @param requestCode
//     * @param permissions
//     * @param grantResults
//     */
//    @Override
//    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
//        if (requestCode == PermissionManager.REQUEST_CODE_ASK_LOCATION_PERMISSIONS) {
//            if ((grantResults.length == 2 && grantResults[0] == PackageManager.PERMISSION_GRANTED
//                    && grantResults[1] == PackageManager.PERMISSION_GRANTED)) {
////                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
//            } else {
//                Logs.e("SplashAct", "We highly recommend that you need to grant the special permissions before initializing the SDK, otherwise some "
//                        + "functions will not work");
////                MessageTools.showToast(getApplicationContext(), "您未开启定位权限，禁止该权限会导致app某些功能异常");
////                PushManager.getInstance().initialize(this.getApplicationContext(), userPushService);
//            }
//        } else {
//            super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//        }
//
//        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//    }
}
